package com.xt.back.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xt.back.constant.ResultDTO;
import com.xt.back.dto.CourseMappingDto;
import com.xt.back.entity.CourseMapping;
import com.xt.back.entity.Relation;
import com.xt.back.exception.OperateException;
import com.xt.back.service.ICourseMappingService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 用户课程关联表 前端控制器
 * </p>
 *
 * @author leotong
 * @since 2022-04-03
 */
@CrossOrigin
@RestController
@AllArgsConstructor
@RequestMapping("/back/courseMapping")
public class CourseMappingController {

    private ICourseMappingService courseMappingService;

    @PostMapping("/add")
    public ResultDTO<Boolean> addCourseMapping(@RequestBody CourseMapping courseMapping){
        if (courseMapping==null){
            throw new OperateException("选课信息不能为空");
        }
        if (courseMapping.getCourseId()==null){
            throw new OperateException("课程信息不能为空");
        }
        if (courseMapping.getUserId()==null){
            throw new OperateException("用户信息不能为空");
        }
        LambdaQueryWrapper<CourseMapping> courseMappingQueryWrapper=new LambdaQueryWrapper<CourseMapping>();
        courseMappingQueryWrapper.eq(CourseMapping::getUserId,courseMapping.getUserId()).eq(CourseMapping::getCourseId,courseMapping.getCourseId());
        CourseMapping one = courseMappingService.getOne(courseMappingQueryWrapper);
        if (one!=null){
            throw new OperateException("当前用户已经选择过该课程，请重新指定");
        }
        courseMapping.setCreateTime(LocalDateTime.now());
        return ResultDTO.success(courseMappingService.save(courseMapping));
    }

    @GetMapping("/remove")
    public ResultDTO<Boolean> deleteCourseMapping(int id){
        return ResultDTO.success(courseMappingService.removeById(id));
    }

    @PostMapping("/update")
    public ResultDTO<Boolean> updateCourseMapping(@RequestBody CourseMapping courseMapping){
        return ResultDTO.success(courseMappingService.updateById(courseMapping));
    }

    @PostMapping("/getCourseMappingByPage")
    public ResultDTO<Page<CourseMappingDto>> getCourseMappingByPage(@RequestBody CourseMapping courseMapping){
        return ResultDTO.success(courseMappingService.getCourseMappingByPage(courseMapping));
    }

    @GetMapping("/getAllCourseMapping")
    public ResultDTO<List<CourseMappingDto>> getAllCourseMapping(){
        return ResultDTO.success(courseMappingService.getAllCourseMapping());
    }
}
